package com.mchsdk.paysdk.http.request;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONException;
import org.json.JSONObject;

import com.mchsdk.paysdk.common.Constant;
import com.mchsdk.paysdk.entity.ZFBVerificationResult;
import com.mchsdk.paysdk.http.RequestUtil;
import com.mchsdk.paysdk.utils.Base64;
import com.mchsdk.paysdk.utils.MCErrorCodeUtils;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.OrderInfoUtils;
import com.mchsdk.paysdk.utils.PaykeyUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

public class ZFBOrderInfoRequest {

    private static final String TAG = "ZFBOrderInfoRequest";

    HttpUtils http;
    Handler mHandler;

    public ZFBOrderInfoRequest(Handler mHandler) {
        http = new HttpUtils();
        if (null != mHandler) {
            this.mHandler = mHandler;
        }
    }

    public void post(String url, RequestParams params) {
        MCLog.e(TAG, "fun#post url = " + url);
        if (TextUtils.isEmpty(url) || null == params) {
            MCLog.e(TAG, "fun # post url is null or params is null");
            noticeResult(Constant.ZFB_PAY_VALIDATE_FAIL, "客户端的支付宝请求参数为空");
            return;
        }
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response = RequestUtil.getResponse(responseInfo);
                ZFBVerificationResult zfbPayResult = new ZFBVerificationResult();
                try {
                    JSONObject json = new JSONObject(response);
                    String msg;
                    int status = json.optInt("status");
                    if (status==0) {//UC账号不支持
                        if (!TextUtils.isEmpty(json.optString("return_msg"))) {
                            msg = json.optString("return_msg");
                        } else {
                            msg = MCErrorCodeUtils.getErrorMsg(status);
                        }
                        MCLog.e(TAG, "msg:" + msg);
                        noticeResult(Constant.ZFB_PAY_VALIDATE_FAIL, msg);
                        return;
                    }
                    // MCLog.e(TAG, "request message:" +
                    // json.optString("orderInfo"));
                    String orderInfo = json.optString("orderInfo");
                    String md5Sign = json.optString("md5_sign");
                    String orderSign = json.optString("order_sign");
                    zfbPayResult.setSign(orderSign);
                    zfbPayResult.setZfbMd5Key(md5Sign);
                    zfbPayResult.setOrderInfo(orderInfo);
                    zfbPayResult.setOrderNumber(json.optString("out_trade_no"));
                    String tempmd5 = PaykeyUtil.stringToMD5(orderInfo + OrderInfoUtils.MCH_MD5KEY());
                    MCLog.e(TAG, "tempmd5 = " + tempmd5 + " ?= " + md5Sign);
                    if (tempmd5.equals(md5Sign)) {
                        String signStr = new String(Base64.decode(orderInfo), "utf-8");
                        zfbPayResult.setOrderInfo(signStr);
                        if (!TextUtils.isEmpty(orderSign)) {
                            String sign = URLEncoder.encode(orderSign, "UTF-8");
                            zfbPayResult.setSign(sign);
                        }
                        noticeResult(Constant.ZFB_PAY_VALIDATE_SUCCESS, zfbPayResult);
                    } else {
                        noticeResult(Constant.ZFB_PAY_VALIDATE_FAIL, "订单验证失败");
                    }
                } catch (JSONException e) {
                    noticeResult(Constant.ZFB_PAY_VALIDATE_FAIL, "服务器异常");
                    MCLog.e(TAG, "fun#post JSONException:" + e);
                } catch (UnsupportedEncodingException e) {
                    noticeResult(Constant.ZFB_PAY_VALIDATE_FAIL, "支付宝验证异常");
                } catch (Exception e) {
                    noticeResult(Constant.ZFB_PAY_VALIDATE_FAIL, "服务器异常：" + e);
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                MCLog.e(TAG, "onFailure" + msg);
                MCLog.e(TAG, "error" + error.getExceptionCode());
                noticeResult(Constant.ZFB_PAY_VALIDATE_FAIL, "网络异常");
            }
        });
    }

    private void noticeResult(int type, Object obj) {
        Message msg = new Message();
        msg.what = type;
        msg.obj = obj;
        if (null != mHandler) {
            mHandler.sendMessage(msg);
        }
    }
}
